"""
佣金结算
"""
import os
import sys
import django
import datetime

base_url = os.path.split(os.path.split(os.getcwd())[0])[0]
print(base_url)
sys.path.insert(0, os.path.split(os.path.split(os.getcwd())[0])[0])
os.environ['DJANGO_SETTINGS_MODULE'] = 'finance_c2c.settings'
django.setup()

from apps.supply_order.models import WomaiOrder
from apps.supply_order.models import WomaiChildOrder
from apps.supply_order.models import OrderIncome
from core.tools.get_datetime import GetDateTime
from django.db.models import Q

from django.contrib.auth import get_user_model

userModel = get_user_model()


class Commission(object):
    # 确认收货
    @staticmethod
    def confirm_order():
        days_ago_15 = GetDateTime.get_days_ago(15)
        # 小于15天，状态为待收货的订单
        queryset = WomaiOrder.objects.filter(supply_order__created_time__lt=days_ago_15, order_status=3)
        # 确认收货
        queryset.update(
            order_status=4  # 修改订单状态 订单已完成
        )
        return queryset

    # 结算佣金
    @staticmethod
    def balance_income():
        # 换货成功
        days_ago_30 = GetDateTime.get_days_ago(30)
        # 子订单中过滤出主订单是订单已完成的，并且不需要售后，或者换货成功，时间大于30天
        days_ago_15 = GetDateTime.get_days_ago(15)
        # after_sale = 3  换货成功 after_sale 拒绝售后  after_sale 0 不需要售后
        child_order = WomaiChildOrder.objects.filter(
            Q(after_sale=3, wm_order__supply_order__created_time__lt=days_ago_30) | Q(after_sale=0,
                                                                                      wm_order__supply_order__created_time__lt=days_ago_15) | Q(
                after_sale=5, wm_order__supply_order__created_time__lt=days_ago_15),
        )
        child_order_ids = child_order.values_list("id", flat=True)
        # 交易成功的子订单，并且收益状态是未结算的
        income_queryset = OrderIncome.objects.filter(order_id__in=child_order_ids, submit_state=1)
        # income_type1_queryset = income_queryset.filter(income_type=1)  # 只找上下级的收益
        # for i in income_type1_queryset:
        #     # 更新绩效
        #     i.base_order.user.update_user_perf(i.order.total_fee)
        # # 获取升级用户
        # level_up_list = []
        # for i in income_queryset:
        #     # 升级
        #     result = i.user.level_up_by_sales()
        #     if result:
        #         level_up_list.append(i.user)
        # # 判断掉队
        # for i in level_up_list:
        #     i.drop_out()
        income_queryset.update(
            submit_state=2  # 修改成已结算
        )

if __name__ == '__main__':
    Commission.confirm_order()
    Commission.balance_income()
    # user = userModel.objects.get(id=5)
    # amount, queryset = OrderIncome.objects.transfer_income(user)
    # print(amount, queryset.query, queryset)
